package model

import (
	"context"
	app "im-demo/application"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

var CurCollection *mongo.Collection

type SessionList struct {
	OwnerId        string  `json:"owner_id" bson:"owner_id"`                 // 自己的id
	OtherId        string  `json:"other_id" bson:"other_id"`                 // 对方的id
	Nickname       string  `json:"nickname" bson:"nickname"`                 // 对方昵称，不用每次都去获取对方的信息
	Avator         string  `json:"avator" bson:"avator"`                     // 对方头像，用每次都去获取对方的信息
	MsgTypt        int     `json:"msg_type" bson:"msg_type"`                 // 消息类型
	UnreadMsgCount int     `json:"unread_msg_count" bson:"unread_msg_count"` // 未读消息数量
	LastTime       int64   `json:"last_time" bson:"last_time"`               // 最后一条消息时间
	LastMsgId      int64   `json:"last_msg_id" bson:"last_msg_id"`           // 最后一条消息id
	LastMsg        Message `json:"last_msg" bson:"last_msg"`                 // 最后一条消息
}

type UpdateData struct {
	OwnerId   string  `json:"owner_id"`
	OtherId   string  `json:"other_id"`
	LastTime  int64   `json:"last_time"`
	LastMsgId int64   `json:"last_msg_id"`
	LastMsg   Message `json:"last_msg"`
}

func init() {
	CurCollection = app.MongoDBClient.Database(app.MongoDataBaseName).Collection(app.MongoSessionListCollection)
}

// CreateSession 创建会话列表
func CreateSession(s SessionList) (*mongo.InsertOneResult, error) {
	return CurCollection.InsertOne(context.TODO(), s)
}

// IncUnreadMsgCount 未读消息+1
func IncUnreadMsgCount(OwnerId, OtherId string) (interface{}, error) {
	filter := bson.M{
		"owner_id": OwnerId,
		"other_id": OtherId,
	}
	update := bson.M{
		"$inc": bson.M{
			"unread_msg_count": 1,
		},
	}
	result, err := CurCollection.UpdateOne(context.TODO(), filter, update)
	if err != nil {
		return nil, err
	}

	return result.UpsertedID, nil
}

// ResetUnreadMsgCount 清空未读消息
func ResetUnreadMsgCount(OwnerId, OtherId string) (interface{}, error) {
	filter := bson.M{
		"owner_id": OwnerId,
		"other_id": OtherId,
	}
	update := bson.M{
		"$set": bson.M{
			"unread_msg_count": 0,
		},
	}
	return CurCollection.UpdateOne(context.TODO(), filter, update)
}

// DelSession 删除会话列表
func DelSession(ownerId, otherId string) (*mongo.DeleteResult, error) {
	filter := bson.M{
		"owner_id": ownerId,
		"other_id": otherId,
	}
	return CurCollection.DeleteOne(context.TODO(), filter)
}

// UpdateSession 更新会话列表
func UpdateSession(data *UpdateData) error {
	ownerFilter := bson.M{
		"owner_id": data.OwnerId,
		"other_id": data.OtherId,
	}
	otherFilter := bson.M{
		"owner_id": data.OtherId,
		"other_id": data.OwnerId,
	}
	update := bson.M{
		"$set": bson.M{
			"last_time":   data.LastTime,
			"last_msg_id": data.LastMsgId,
			"last_msg":    data.LastMsg,
		},
	}
	_, err := CurCollection.UpdateOne(context.TODO(), ownerFilter, update)
	if err != nil {
		return err
	}

	_, err = CurCollection.UpdateOne(context.TODO(), otherFilter, update)
	if err != nil {
		return err
	}

	return nil
}

// GetOwnerSession 获取自己的会话列表
func GetOwnerSession(OwnerID string) ([]*SessionList, error) {
	filter := bson.M{
		"owner_id": OwnerID,
	}
	var results []*SessionList
	cur, err := CurCollection.Find(context.TODO(), filter)
	if err != nil {
		return nil, err
	}
	defer cur.Close(context.TODO())

	for cur.Next(context.TODO()) {
		var elem SessionList
		err := cur.Decode(&elem)
		if err != nil {
			return nil, err
		}
		results = append(results, &elem)
	}

	if err := cur.Err(); err != nil {
		return nil, err
	}

	return results, nil
}

//
func GetAllSession() ([]*SessionList, error) {
	filter := bson.M{}
	var results []*SessionList
	cur, err := CurCollection.Find(context.TODO(), filter)
	if err != nil {
		return nil, err
	}
	defer cur.Close(context.TODO())

	for cur.Next(context.TODO()) {
		var elem SessionList
		err := cur.Decode(&elem)
		if err != nil {
			return nil, err
		}
		results = append(results, &elem)
	}

	if err := cur.Err(); err != nil {
		return nil, err
	}

	return results, nil
}
